package com.stores.action;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.stores.model.Datastore;
import com.stores.model.Manufacturer;

public class ManageManufacturerAction {

	/***
	 * 
	 * @param category
	 */
	public void Create(Manufacturer category) {
		DatastoreService datastore = Datastore.get();
		Entity mfgEntity = new Entity(Manufacturer.class.getSimpleName());
		mfgEntity.setProperty("name", category.getName());
		mfgEntity.setProperty("description", category.getDescription());

		datastore.put(mfgEntity);
	}

	/**
	 * 
	 * @param category
	 * @return
	 */
	public boolean Update(Manufacturer category) {
		DatastoreService datastore = Datastore.get();
		Query mfgQuery = new Query(Manufacturer.class.getSimpleName());
		mfgQuery.addFilter(Entity.KEY_RESERVED_PROPERTY, FilterOperator.EQUAL,
				KeyFactory.createKey(Manufacturer.class.getSimpleName(),
						category.getId()));
		PreparedQuery query = datastore.prepare(mfgQuery);
		Entity mfgEntity = query.asSingleEntity();
		if (mfgEntity == null) {
			return false;
		} else {
			mfgEntity.setProperty("name", category.getName());
			mfgEntity.setProperty("description", category.getDescription());
			datastore.put(mfgEntity);
		}
		return true;
	}

	/**
	 * 
	 * @return
	 */
	public List<Manufacturer> Retrive() {
		DatastoreService datastore = Datastore.get();
		Query mfgQuery = new Query(Manufacturer.class.getSimpleName());
		PreparedQuery query = datastore.prepare(mfgQuery);
		Iterable<Entity> mfgEntities = query.asIterable();

		List<Manufacturer> mfgs = new ArrayList<Manufacturer>();

		for (Entity c : mfgEntities) {
			Manufacturer mfg = new Manufacturer();
			mfg.setId(c.getKey().getId());
			mfg.setName(c.getProperty("name").toString());
			mfg.setDescription(c.getProperty("description").toString());
			mfgs.add(mfg);
		}
		return mfgs;
	}

}
